Ext.extend(app.module,{
    allQuestions: [],
    myQuestions:[],
    myAnswers: [],
    total: 0,
    questionIndex: 0,
    taskSave:{},
    taskKs:{},
    time:0,
    init: function(){
        main = this;
        this.ds = new Ext.data.Store({
            proxy: new Ext.data.HttpProxy({url:'paper/getPaperforKs.do'}),
            reader: new Ext.data.JsonReader({
                root: 'rows',
                idProperty: 'id'
            },[
                {name:'id'},
                {name:'name'},
                {name:'kemuid'},
                {name:'kemuname'},
                {name:'state'},
                {name:'addtime'},
                {name:'starttime'},
                {name:'kstime'},
                {name:'scorestate'}
            ])
        });
        this.body = new Ext.grid.GridPanel({
            store: this.ds,
            region: 'center',
            loadMask: true,
            viewConfig:{
                forceFit:true
            },
            sm: this.sm,
            columns: [
                new Ext.grid.RowNumberer(),
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'name',
                    header: '试卷名称'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'kemuname',
                    header: '科目'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'state',
                    header: '试卷状态',
                    renderer: function(value,cellmeta,record,rowIndex,columnIndex,store){
                        if(value==1){
                            return "考试还未开始";
                        } else if (value==2) {
                            return "考试正在进行";
                        } else if (value==3) {
                            return "考试已经结束";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'scorestate',
                    header: '考试状态',
                    renderer: function(value){
                        if (value==0){
                            return "还未开始考试";
                        } else if(value==1){
                            return "已打开过试卷";
                        } else if (value==2) {
                            return "已上传文件，未交卷";
                        } else if (value==3){
                            return "未上传文件，已经交卷";
                        } else if (value==4){
                            return "已上传文件，已交卷";
                        } else {
                            return "";
                        }
                    }
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'starttime',
                    header: '考试时间'
                },
                {
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'kstime',
                    header: '考试时长'
                },{
                    xtype: 'gridcolumn',
                    align: 'center',
                    dataIndex: 'id',
                    header: '参加考试',
                    renderer: function(value,cellmeta,record,rowIndex,columnIndex,store){
                        if (record.data.scorestate==0){
                            return "<input type='button' value='参加考试' onclick='main.startKs("+value+");' />";
                        } else if(record.data.scorestate==1 || record.data.scorestate==2){
                            if(record.data.state==1){
                                return "<input type='button' value='上传文件' onclick='main.getUploadDlg("+record.data.id+");' />";
                            } else {
                                return "<input type='button' value='继续考试' onclick='main.startKs("+value+");' />";
                            }
                        } else if(record.data.scorestate==3){
                            return "<input type='button' value='上传文件' onclick='main.getUploadDlg("+record.data.id+");' />";
                        } else {
                            return "";
                        }
                    }
                }
            ]
        });
        this.main.add(this.body);
        this.main.doLayout();
        this.ds.load();
    },
    startKs: function(id){
        Ext.Ajax.request({
            method:'POST',
            url: 'ks/startKs.do',
            params: {paperid:id},
            scope: this,
            async: false,   //改为同步请求，给全局变量赋值
            success: function(response){
                var json = Ext.util.JSON.decode(response.responseText);
                if(!(json.info==undefined || json.info=='')){
                    Ext.Msg.alert('提示', json.info);
                    this.ds.reload();
                } else {
                    this.allQuestions = json.all;
                    this.total = this.allQuestions.length;
                    this.myQuestions = Ext.util.JSON.decode(json.question);
                    this.time = parseInt(json.time);
                    var minutes = parseInt(this.time/60);
                    var seconds = this.time-minutes*60;
                    if(json.myAnswer!=""){
                        this.myAnswers = Ext.util.JSON.decode(json.myAnswer);
                    }
                    this.getDlg();
                    this.getNextQuestion();
                    Ext.getCmp('ksminutes').setValue(minutes);
                    Ext.getCmp('ksseconds').setValue(seconds);
                    Ext.getCmp('paperIdText').setValue(id);
                    Ext.getCmp('myQuestionText').setValue(json.myAnswer);
                    this.taskSave = {
                        run: this.saveAnswer,       //执行任务时执行的函数
                        interval: 30000             //任务间隔，毫秒为单位，这里是30秒
                    };
                    Ext.TaskMgr.start(this.taskSave); //启动定时任务
                    this.taskKs = {
                        scope: this,
                        run: this.daojishi,       //执行任务时执行的函数
                        interval: 1000             //任务间隔，毫秒为单位，这里是1秒
                    };
                    Ext.TaskMgr.start(this.taskKs);
                }
            },
            failure: function(form, action) {
                var info = action.result.info;
                Ext.Msg.alert('提示', info);
            }
        });
    },
    //定时保存及对时
    saveAnswer: function(){
        Ext.Ajax.request({
            method:'POST',
            url: 'ks/saveAnswer.do',
            params: {paperid:Ext.getCmp('paperIdText').getValue(),kgtda:Ext.getCmp('myQuestionText').getValue()},
            disableCaching: true,   //禁用缓存
            async: false,   //改为同步请求，给全局变量赋值
            scope: this,
            success: function(response){
                var json = Ext.util.JSON.decode(response.responseText);
                if(!(json.info==undefined || json.info=='')){
                    Ext.Msg.alert('提示', json.info);
                } else {
                    if(json.myAnswer!=""){
                        this.myAnswers = Ext.util.JSON.decode(json.myAnswer);
                    }
                        this.time = parseInt(json.time);
                        var minutes = parseInt(this.time/60);
                        var seconds = this.time-minutes*60;
                        Ext.getCmp('ksminutes').setValue(minutes.toString());
                        Ext.getCmp('ksseconds').setValue(seconds.toString());

                }
            },
            failure: function(form, action) {
                var info = action.result.info;
                Ext.Msg.alert('提示', info);
            }
        });
    },
    getDlg: function(){
        var form = new Ext.form.FormPanel({
            id: 'questionForm',
            defaultType: 'textfield',
            bodyStyle: 'padding:5px',
            buttonAlign: 'center',
            url:'score/submitPaper.do',
            labelWidth: 80,
            submitEmptyText: false,     //禁止提交emptyText
            defaults: {
                anchor: '100%'
            },
            items: [
                {
                    xtype: 'hidden',
                    id: 'paperIdText',
                    fieldLabel: 'Label'
                },
                {
                    xtype: 'hidden',
                    id: 'myQuestionText',
                    fieldLabel: 'Label'
                },
                {
                    xtype: 'hidden',
                    name: 'id',
                    id: 'questionId',
                    fieldLabel: 'Label'
                },
                {
                    xtype: 'compositefield',
                    fieldLabel: '倒计时',
                    combineErrors: false,
                    items: [
                        {
                            id: 'ksminutes',
                            xtype: 'displayfield',
                            width: 36
                        },
                        {
                            xtype: 'displayfield',
                            value: '分'
                        },
                        {
                            id: 'ksseconds',
                            xtype: 'displayfield',
                            width: 36
                        },
                        {
                            xtype: 'displayfield',
                            value: '秒'
                        }
                    ]
                },
                {
                    xtype: 'displayfield',
                    value: '',
                    id: 'timuShuliang',
                    name:'title',
                    fieldLabel: '题目数量'
                },
                {
                    xtype: 'displayfield',
                    value: '',
                    id: 'timuYaoqiu',
                    name:'title',
                    fieldLabel: '题目要求'
                },
                {
                    xtype: 'displayfield',
                    value: '',
                    id: 'questionTitle',
                    name:'title',
                    fieldLabel: '题干'
                }
            ],
            buttons: [
                {
                    text: '上一题',
                    handler: function() {
                        main.getLastQuestion();
                    }
                },
                {
                    text: '下一题',
                    handler: function() {
                        main.getNextQuestion();
                    }},
                '->',
                {
                    text: '上传操作题',
                    scope: this,
                    handler: function() {
                        main.getUploadDlg(Ext.getCmp('paperIdText').getValue());
                    }
                },
                {
                    text: '交卷',
                    scope: this,
                    handler: function(){
                        main = this;
                        Ext.Msg.confirm('重置密码', '确认将提交试卷，不能再进入？',
                            function(btn) {
                                if (btn == 'yes') {
                                    main.submit();
                                }
                            }
                        );
                    }
                }
            ]
        });
        if(!this.dlg){
            this.dlg = new Ext.Window({
                id:'maindlg',
                height: 480,
                width: 620,
                layout: 'fit',
                border: false,
                frame: true,
                title: '开始考试',
                closeAction: 'hide',    //考虑此处改下？
                modal: true,
                plain: true,
                resizable: false,
                closable: false,
                items: [form],
                listeners: {
                    scope: this,
                    render: function(fp){
                        form.getForm().waitMsgTarget = fp.getEl();
                    },
                    show: function(){
                        var f = form.getForm();
                        f.clearInvalid();
                    }
                }
            });
        }
        this.dlg.show();
    },
    getAnswerField: function(type,question,index){
        var answerFieldSet = new Ext.form.FieldSet({
            title:'答案',
            autoHeight: true,
            name: 'answer',
            autoDestroy: true,  //自动销毁容器下组件
            id: 'answerFieldSet'
        });
        if(type==1){
            answerFieldSet.add(this.getDanxuan(question,index));
        } else if(type==2){
            answerFieldSet.add(this.getduoxuan(question,index));
        } else if(type==3){
            answerFieldSet.add(this.getpanduan(question,index));
        } else if(type==4||type==5||type==6){
            answerFieldSet.setTitle('下载操作题素材');
            answerFieldSet.add(this.getcaozuo(question,index));
        }
        return answerFieldSet;
    },
    isCheck: function(questionId,answerId){
        var isChecked = false;
        for(var i=0;i<this.myAnswers.length;i++){
            if(questionId==this.myAnswers[i].id){
                var answers = this.myAnswers[i].answer.split(",");
                for(var j=0;j<answers.length;j++){
                    if(answerId==parseInt(answers[j])){
                        isChecked = true;
                        break;
                    }
                }
            }
        }
        return isChecked;
    },
    getDanxuan: function(question,index){
        var answers = question.answers;
        var textArray = new Array(4);
        var valueArray = new Array(4);
        var isCheckedArray = new Array(4);
        var arr = this.myQuestions[index-1].answer.split(",");
        for(var i=0;i<arr.length;i++){
            for(var j=0;j<answers.length;j++){
                if(parseInt(arr[i])==answers[j].id){
                    textArray[i] = answers[j].answer;
                    valueArray[i] = answers[j].id;
                    isCheckedArray[i] = this.isCheck(question.id,answers[j].id);
                    break;
                }
            }
        }
        var radioGroup = new Ext.form.RadioGroup({
            columns: 1,
            items: [
                {
                    xtype: 'radio',
                    id:'danxuanRadio',
                    name: 'radio',
                    boxLabel: textArray[0],
                    inputValue:valueArray[0],
                    checked: isCheckedArray[0]
                },
                {
                    xtype: 'radio',
                    name: 'radio',
                    boxLabel: textArray[1],
                    inputValue:valueArray[1],
                    checked: isCheckedArray[1]
                },
                {
                    xtype: 'radio',
                    name: 'radio',
                    boxLabel: textArray[2],
                    inputValue:valueArray[2],
                    checked: isCheckedArray[2]
                },
                {
                    xtype: 'radio',
                    name: 'radio',
                    boxLabel: textArray[3],
                    inputValue:valueArray[3],
                    checked: isCheckedArray[3]
                }
            ]
        });
        return radioGroup;
    },
    getduoxuan: function(question,index){
        var answers = question.answers;
        var textArray = new Array(4);
        var valueArray = new Array(4);
        var isCheckedArray = new Array(4);
        var arr = this.myQuestions[index-1].answer.split(",");
        for(var i=0;i<arr.length;i++){
            for(var j=0;j<answers.length;j++){
                if(parseInt(arr[i])==answers[j].id){
                    textArray[i] = answers[j].answer;
                    valueArray[i] = answers[j].id;
                    isCheckedArray[i] = this.isCheck(question.id,answers[j].id);
                    break;
                }
            }
        }
        var checkboxGroup = new Ext.form.CheckboxGroup({
            columns: 1,id:'duoxuanCheckbox',
            items: [
                {
                    xtype: 'checkbox',
                    name: 'checkbox',
                    boxLabel: textArray[0],
                    value:valueArray[0],
                    checked: isCheckedArray[0]
                },
                {
                    xtype: 'checkbox',
                    name: 'checkbox',
                    boxLabel: textArray[1],
                    value:valueArray[1],
                    checked: isCheckedArray[1]
                },
                {
                    xtype: 'checkbox',
                    name: 'checkbox',
                    boxLabel: textArray[2],
                    value:valueArray[2],
                    checked: isCheckedArray[2]
                },
                {
                    xtype: 'checkbox',
                    name: 'checkbox',
                    boxLabel: textArray[3],
                    value:valueArray[3],
                    checked: isCheckedArray[3]
                }
            ]
        });
        return checkboxGroup;
    },
    getpanduan: function(question,index){
        var answers = question.answers;
        var textArray = new Array(2);
        var valueArray = new Array(2);
        var isCheckedArray = new Array(4);
        var arr = this.myQuestions[index-1].answer.split(",");
        for(var i=0;i<arr.length;i++){
            for(var j=0;j<answers.length;j++){
                if(parseInt(arr[i])==answers[j].id){
                    textArray[i] = answers[j].answer;
                    valueArray[i] = answers[j].id;
                    isCheckedArray[i] = this.isCheck(question.id,answers[j].id);
                    break;
                }
            }
        }
        var radioGroup = new Ext.form.RadioGroup({
            columns: 1,
            items: [
                {
                    xtype: 'radio',
                    id:'panduanRadio',
                    name: 'radio',
                    boxLabel: textArray[0],
                    inputValue:valueArray[0],
                    checked: isCheckedArray[0]
                },
                {
                    xtype: 'radio',
                    name: 'radio',
                    boxLabel: textArray[1],
                    inputValue:valueArray[1],
                    checked: isCheckedArray[1]
                }
            ]
        });
        return radioGroup;
    },
    getcaozuo: function(question,index){
        main = this;
        return new Ext.form.DisplayField({
            value:"<a style=\"color:red;font-size:14pt\" href=\"ks\/downloadFile.do?filename="+question.filename+"\">点我下载素材<\/a>"
        });
    },
    getUploadDlg: function(paperid){
        var main = this;
        var form = new Ext.form.FormPanel({
            labelAlign: 'right',
            bodyStyle: 'padding:5px',
            buttonAlign: 'right',
            frame: true,
            fileUpload: true,
            url:'ks/uploadResult.do',
            labelWidth: 80,
            allowBlank: false,
            msgTarget: 'side',
            defaults: {
                anchor: '90%'
            },
            items: [
                {
                    xtype: 'textfield',
                    name: 'file',
                    id: 'studentExcel',
                    fieldLabel: '选择文件',
                    inputType: 'file'
                }
            ],
            buttons: [{
                text: '提交',
                scope: this,
                handler: function() {
                    if (form.getForm().isValid()) {
                        var filePath = Ext.getCmp('studentExcel').getValue();
                        var parts = filePath.split(".");
                        var result;
                        if(parts.length>1){
                            result = parts.pop();   //取出数组最后一个元素
                        }
                        if(!(result=="rar" || result=="zip")){
                            Ext.Msg.alert("提示","只能上传.rar和.zip后缀的压缩文件！");
                        } else {
                            form.getForm().submit({
                                //waitTitle: '保存数据',
                                //waitMsg: '正在保存……',
                                scope: this,
                                method: 'POST',
                                params: {paperid:paperid},
                                submitEmptyText: false,     //禁止提交emptyText
                                success: function(form, action) {
                                    if (action.result.success) {
                                        Ext.Msg.alert('信息', action.result.success);
                                    } else {
                                        Ext.Msg.alert('信息', action.result.inf);
                                    }
                                    dlg.close();
                                    this.ds.reload();
                                },
                                failure: function(form, action) {
                                    Ext.Msg.alert('提示', action.result.info);
                                }
                            });
                        }
                    }
                }
            }]
        });
        var dlg = new Ext.Window({
            height: 140,
            width: 500,
            layout: 'fit',
            border: false,
            frame: true,
            title: '上传文件',
            modal: true,
            plain: true,
            resizable: false,
            items: [form],
            listeners: {
                scope: this,
                render: function(fp){
                    form.getForm().waitMsgTarget = fp.getEl();
                },
                show: function(){
                    var f = form.getForm();
                    f.clearInvalid();
                }
            }
        });
        dlg.show();
    },
    getLastQuestion: function(){
        if(this.questionIndex==1){
            Ext.Msg.alert("提示","已经是第一道题了！");
            return;
        }
        this.changeQuestion(this.questionIndex-1);
    },
    getNextQuestion: function(){
        if(this.questionIndex!=0){
            if(this.questionIndex==this.total){
                Ext.Msg.alert("提示","已经是最后一题了！");
                return;
            }
        }
        this.changeQuestion(this.questionIndex+1);
    },
    changeQuestion: function(index){
        //开始处理当前题目结果保存
        //取出当前的值进行保存，第一次加载窗口this.questionIndex==0，不保存
        if(this.questionIndex!=0){
            var thatQuestion;
            var theQuestionId = this.myQuestions[this.questionIndex-1].id;
            for(var i=0;i<this.total;i++){
                if(theQuestionId==this.allQuestions[i].id){
                    type = this.allQuestions[i].type;   //找到文件类型
                    break;
                }
            }
            //单选、多选、判断需要自动保存答案
            if(type==1){
                var myOneAnswer = Ext.getCmp('danxuanRadio').getGroupValue();
                if(!(myOneAnswer==undefined || myOneAnswer==null)){
                    this.saveJson(theQuestionId,myOneAnswer.toString());
                }
            } else if (type==2) {
                var temp = Ext.getCmp('duoxuanCheckbox').getValue();
                //如果数组的值>0，证明有选中
                if(temp.length>0){
                    var myOneAnswer = new Array();
                    for(var i=0;i<temp.length;i++){
                        //此处要注意对象的里值名称为value
                        myOneAnswer.push(temp[i].value);
                    }
                    this.saveJson(theQuestionId,myOneAnswer.join(","));
                }
            } else if(type==3){
                var myOneAnswer = Ext.getCmp('panduanRadio').getGroupValue();
                if(!(myOneAnswer==undefined || myOneAnswer==null)){
                    this.saveJson(theQuestionId,myOneAnswer.toString());
                }
            }
        }
        //开始显示下一题
        this.questionIndex = index;
        //索引从0开始
        var theOtherQuestionId = this.myQuestions[index-1].id;
        var question;
        Ext.getCmp('questionId').setValue(theOtherQuestionId);
        for(var i=0;i<this.total;i++){
            if(theOtherQuestionId==this.allQuestions[i].id){
                question = this.allQuestions[i];
                Ext.getCmp('timuShuliang').setValue("第"+index+"题，共"+this.total+"题(包括客观题和操作题)，你已经作答<font color='red'>"
                                            +this.myAnswers.length+"</font>道客观题");
                Ext.getCmp('questionTitle').setValue(question.title);
                type = this.allQuestions[i].type;
                break;
            }
        }
        var questionForm = Ext.getCmp('questionForm');
        questionForm.remove(Ext.getCmp('answerFieldSet',true));
        if(type==1){
            questionForm.add(this.getAnswerField(type,question,index));
            Ext.getCmp('timuYaoqiu').setValue("该题目为单选题，只有一个正确项！");
        } else if(type==2){
            questionForm.add(this.getAnswerField(type,question,index));
            Ext.getCmp('timuYaoqiu').setValue("该题目为多选题，有2到4个正确项！");
        } else if(type==3){
            questionForm.add(this.getAnswerField(type,question,index));
            Ext.getCmp('timuYaoqiu').setValue("该题目为判断题，只有一个正确项！");
        } else if(type==4 || type==5 || type==6){
            questionForm.add(this.getAnswerField(type,question,index));
            Ext.getCmp('timuYaoqiu').setValue("该题目为操作题，请先在桌面建立一个文件夹（名称随意），" +
                "下载素材文件到你刚才的建立的文件夹中，<font color='red'>所有</font>操作题做完后<font color='red'>打包压缩</font>并上传！<br />提醒：下载时不要点打开，而是点" +
                "<font color='red'>保存</font>。每做完一个操作题要保存并关闭，确保你在打包压缩时，<font color='red'>word,excel,ppt都关了！</font>");
        }
        questionForm.doLayout();
    },
    saveJson: function(id,answer){
        var flag = false;
        //如果已经存在就修改，否则添加
        for(var i=0;i<this.myAnswers.length;i++){
            if(id==this.myAnswers[i].id){
                flag = true;
                this.myAnswers[i].answer = answer;
            }
        }
        if(!flag){
            var temp = {"id":id,"answer":answer};
            this.myAnswers.push(temp);
        }
        Ext.getCmp('myQuestionText').setValue(Ext.util.JSON.encode(this.myAnswers));
    },
    daojishi: function(){
        this.time -= 1;
        if(this.time<=0){
            this.submit();
        }
        var minutes = parseInt(this.time/60);
        var seconds = this.time%60;
        Ext.getCmp('ksminutes').setValue(minutes);
        Ext.getCmp('ksseconds').setValue(seconds);
    },
    submit: function(){
        this.saveAnswer();
        Ext.Ajax.request({
            method:'POST',
            url: 'ks/end.do',
            params: {paperid:Ext.getCmp('paperIdText').getValue()},
            disableCaching: true,   //禁用缓存
            scope: this,
            success: function(response){
                var json = Ext.util.JSON.decode(response.responseText);
                if(!(json.info==undefined || json.info=='')){
                    Ext.Msg.alert('提示', json.info);
                } else {
                    Ext.TaskMgr.stop(this.taskSave);
                    Ext.TaskMgr.stop(this.taskKs);
                    this.dlg.close();
                    if(json.isUpload==false){
                        Ext.Msg.alert('提示', "交卷成功，不过你还未上传文件！");
                    } else {
                        Ext.Msg.alert('提示', "交卷成功");
                    }
                    this.ds.reload();
                }
            },
            failure: function(form, action) {
                var info = action.result.info;
                Ext.Msg.alert('提示', info);
            }
        });
    }
})